package com.gaussian.property.admin.module.system.controller.system;

import com.gaussian.property.admin.module.system.vo.system.RoleMenuTreeVo;
import com.gaussian.property.module.system.entity.SysMenu;
import com.gaussian.property.module.system.entity.SysUser;
import com.gaussian.property.module.system.service.ISysMenuService;
import com.songqi.common.core.constant.Constants;
import com.gaussian.property.module.system.domain.UserConstants;
import com.songqi.common.core.domain.R;
import com.songqi.common.core.utils.ServletUtils;
import com.songqi.common.core.utils.StringUtils;
import com.songqi.common.log.annotation.Log;
import com.gaussian.property.module.system.enums.BusinessType;
import com.songqi.common.security.model.LoginUser;
import com.songqi.common.security.service.TokenService;
import com.songqi.common.security.utils.SecurityUtils;
import com.songqi.common.web.request.controller.BaseController;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜单信息
 *
 * @author songqi(13776346982)
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController
{
    @Resource
    private ISysMenuService menuService;

    @Resource
    private TokenService tokenService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public R list(SysMenu menu)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = ((SysUser)loginUser.getTokenUser()).getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return R.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public R getInfo(@PathVariable Long menuId)
    {
        return R.success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public R treeSelect(SysMenu menu)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = ((SysUser)loginUser.getTokenUser()).getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return R.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public R roleMenuTreeSelect(@PathVariable("roleId") Long roleId)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<SysMenu> menus = menuService.selectMenuList(((SysUser)loginUser.getTokenUser()).getUserId());
        RoleMenuTreeVo roleMenuTreeVo = new RoleMenuTreeVo();
        roleMenuTreeVo.setMenus(menuService.buildMenuTreeSelect(menus));
        roleMenuTreeVo.setCheckedKeys(menuService.selectMenuListByRoleId(roleId));
        return R.success(roleMenuTreeVo);
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            //菜单名称已存在
            return R.error("菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {   //地址必须以http(s)://开头
            return R.error("menu.path.start.with.http");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            //菜单名称已存在
            return R.error("菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            //地址必须以http(s)://开头
            return R.error("menu.path.start.with.http");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            //上级菜单不能选择自己
            return R.error("super.menu.cannot.select.itself");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public R remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            //存在子菜单,不允许删除
            return R.error("submenus.exist.and.cannot.be.deleted");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            //菜单已分配,不允许删除
            return R.error("菜单已被分配给角色，不能删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }
}
